import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpResponse,
  HttpErrorResponse,
  HttpHeaders
} from '@angular/common/http';
import { Observable, tap } from 'rxjs';
import { debugLog } from '../utils/log';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { ActivatedRoute, Router } from '@angular/router';
import { UserInfoService } from '../service/user-info/user-info.service';
import { MessageService } from '../service/message.service';
import { aesReq } from '../utils/utils';

export enum StatusCodeEnum{
  'Forbidden' = 403,
  'Unauthorized' = 401,
  'NotFound' = 404,
  'Timeout' = 504,
  'InternalServerError' = 500
}

@Injectable()
export class MyInterceptorInterceptor implements HttpInterceptor {

  constructor(
    private message: MessageService,
    private modal: NzModalService,
    private router: Router,
    private route: ActivatedRoute,
    private userInfo: UserInfoService
  ) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // console.log('request ===>', request)
    let secureReq = request
    if(request.body && (request.body as any).isSecret === true){
      secureReq = request.clone({
        body: aesReq(request.body),
        // headers: new HttpHeaders({ 'Content-Type': 'application/json' })
      });
    }
    return next.handle(secureReq).pipe(tap({
      next: (event) => {
        if(event instanceof HttpResponse){
          // 请求结果
          // debugLog(event)
          // console.log(event)
        }
      },
      error: (error: HttpErrorResponse) => {
        // debugLog(error)
        // this.message.error('操作失败, 请稍后重试')
        if(error.status === StatusCodeEnum.Forbidden 
            || error.status === StatusCodeEnum.Unauthorized
          ){
          this.userInfo.clearUser()
          this.message.info('当前页面需要登录才可继续操作, 即将跳转登录')
          // this.router.navigate(['/login'])
          this.modal.confirm({
            nzTitle: '当前页面需要登录才可继续操作, 请先登录',
            nzContent: '是否立即登录?',
            // nzOkLoading: true,
            nzOkText: '跳转登录',
            nzOnOk: () => {
              setTimeout(() => {
                this.router.navigate(['/login'])
              }, 0);
            }
          })
        }

        if(error.status === StatusCodeEnum.Timeout){
          this.message.error('服务器异常, 请稍后重试')
        }
        // if(error.status === StatusCodeEnum.InternalServerError){
        //   this.message.createErrorMessage(error)
        // }
      },
      finalize: () => {
        // debugLog('最后始终执行')
      }
    }));
  }

  dealError(){

  }
}
